<template>
  <div>
    <a-row class="oss-manage">
      <a-col :span="5">
        <div class="file-list">
          <!--<a-tree :data="treeData" show-line @select="treeSelect"-->
          <!--:selected-keys="selectedKey"-->
          <!--:default-selected-keys="selectedKey">-->
          <a-tree :data="treeData" @select="treeSelect">
            <template #switcher-icon="node, { isLeaf }">
              <template v-if="node.key === '0'"><IconDriveFile /></template>
              <IconDown v-if="!isLeaf" />
              <!--<IconDriveFile v-if="isLeaf" />-->
            </template>
          </a-tree>
        </div>
      </a-col>
      <a-col :span="19">
        <div class="pic-list">
          <div class="search-box">
            <uploadPicInput
              :data-list="{ directoryPath: apiParams.fileDirectoryId }"
              @onSuccess="uploadPicSuccess"
            />
            <a-input
              v-model="apiParams.name"
              :style="{ width: '320px' }"
              placeholder="查询图片名称"
              allow-clear
              @change="() => init(apiParams)"
            >
              <template #suffix><icon-search /></template>
            </a-input>
          </div>
          <a-checkbox-group
            v-model="selectedOss"
            :default-value="selectedOss"
            @change="selectOssChange"
          >
            <div class="img-box">
              <div
                v-for="(item, index) in ossFileList"
                :key="index"
                class="img-item"
              >
                <a-checkbox :value="item">
                  <template #checkbox="{ checked }">
                    <div
                      class="card"
                      :class="{ 'custom-checkbox-card-checked': checked }"
                      @mouseover="mouseOver(item)"
                      @mouseleave="mouseLeave(item)"
                    >
                      <div className="custom-checkbox-card-mask"
                        ><div className="custom-checkbox-card-mask-dot"></div></div>
                      <img :src="item.url" alt="" />
                      <div
                        v-if="item.isShowPreview"
                        class="preview"
                        @click.prevent="previewClick($event, item)"
                        ><icon-eye size="18"
                      /></div>
                    </div>
                  </template>
                </a-checkbox>
                <div class="text">
                  <a-tooltip :content="item.name"
                    ><div>{{ item.name }}</div></a-tooltip
                  >
                </div>
              </div>
            </div>
          </a-checkbox-group>
          <div class="pagination-box">
            <a-pagination
              :current="apiParams.current"
              :total="apiParams.total"
              :page-size="apiParams.pageSize"
              @change="paginationChange"
            />
          </div>
        </div>
      </a-col>
    </a-row>

    <a-modal v-model:visible="picVisible" title="查看图片" draggable>
      <a-image :src="file.url" width="100%" alt="无效的图片链接"></a-image>
      <template #footer>
        <span>文件类型：{{ file.fileType }} 文件大小：{{ file.msize }}</span>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import {
    onMounted,
    ref,
    nextTick,
    inject,
    h,
    reactive,
    watch
  } from 'vue';
  import {
    IconDriveFile,
    IconDown,
    IconStar,
    IconUp,
  } from '@arco-design/web-vue/es/icon';
  import { getFileDirectory, getFileListData, deleteFile } from '@/api/common';

  import uploadPicInput from '@/components/upload-pic/index.vue';

  const selectedKey = ref(['0']);
  const treeData = ref<any>();
  const ossFileList = ref<any>([]);
  // 传递的参数
  const apiParams = reactive<any>({
    // 搜索框对应data对象
    fileType: 'image',
    pageNumber: 1, // 当前页数
    pageSize: 15, // 页面大小
    sort: 'createTime', // 默认排序字段
    order: 'desc', // 默认排序方式
    startTime: '', // 起始时间
    endTime: '', // 终止时间
    title: '',
    total: 0,
    current: 1,
    fileDirectoryId: '',
    name: '',
  });
  const thumbnailParameter = JSON.parse(
    JSON.stringify({ ...apiParams, pageSize: 15 })
  );
  const selectedOss = ref<any>([]);
  const emit = defineEmits<{
    (e: 'selected', val: any, type?: string): void;
  }>();
  const picVisible = ref(false); // 图片的modal
  const file = ref<any>({}); // 文件数据

  const props = defineProps({
    initialize: {
      type: Boolean,
      default: false,
    },
  });

  // 文件目录格分类式化方法
  const getTree = (tree = [] as any) => {
    const arr = [] as any;
    if (!!tree && tree.length !== 0) {
      // :field-names="{ children: 'children', title: 'directoryName', key: 'id' }"
      tree.forEach((item) => {
        const obj = {} as any;
        obj.title = item.directoryName;
        obj.key = item.id; // 拥有者id
        obj.type = item.directoryType; // 用户类型
        obj.label = item.directoryName;
        obj.level = item.level;
        obj.expand = false;
        obj.selected = false;
        obj.contextmenu = true;
        obj.parentId = item.parentId;
        obj.children = getTree(item.children);
        obj.icon = () => h(IconDriveFile);
        arr.push(obj);
      });
    }
    return arr;
  };
  // 获取文件列表
  const getFileList = () => {
    getFileDirectory().then((res) => {
      if (res.data.success) {
        treeData.value = getTree(res.data.result);
        treeData.value.unshift({
          title: '我的图片',
          label: '我的图片',
          value: '0',
          level: 0,
          children: [],
          id: '0',
          categoryId: 0,
          key: '0',
          // icon: () => h(IconDriveFile)
        });
      }
    });
  };
  // oss资源请求接口
  const init = async (params = apiParams) => {
    const res = await getFileListData(params);
    if (res.data.success) {
      selectedOss.value = [];
      res.data.result.records.forEach((item) => {
        item.selected = false;
      });
      ossFileList.value = res.data.result.records.map((item) => {
        item.isShowPreview = false;
        return item;
      });
      const { current, size, total } = res.data.result;
      apiParams.current = current;
      apiParams.pageSize = size;
      apiParams.total = total;
    }
  };
  // 分页改变
  const paginationChange = (v) => {
    const params = { ...apiParams, pageNumber: v };
    init(params);
  };
  // 复选框值改变时触发
  const selectOssChange = (value) => {
    emit('selected', selectedOss.value);
  };
  const mouseOver = (item) => {
    item.isShowPreview = true;
  };
  const mouseLeave = (item) => {
    item.isShowPreview = false;
  };
  // 预览图片
  const previewClick = (event, v: any) => {
    event.stopPropagation();
    file.value = v;
    file.value.msize = `${((v.fileSize * 1.0) / (1024 * 1024)).toFixed(2)}MB`;
    picVisible.value = true;
  };
  // 选择目录回调
  const treeSelect = (selectedKeys, data) => {
    selectedOss.value = [];
    const id = selectedKeys[selectedKeys.length - 1];
    if (id === '0' || id == 0) {
      delete apiParams.fileDirectoryId;
    } else {
      apiParams.fileDirectoryId = id;
    }
    init(apiParams);
  };

  // 上传文件回调
  const uploadPicSuccess = async (res) =>  {
    let picUrl = res.response.result;
    await init(apiParams);
    nextTick(() => {
      ossFileList.value.forEach((item: any) => {
        if (item.url === picUrl) {
          selectedOss.value.push(item);
          emit('selected', selectedOss.value);
        }
      });
    });
  };



  onMounted(() => {
    // 获取文件列表
    getFileList();
    init();
  });
  // 初始化监听 是否清空所选图片
  watch(() => props.initialize, (val) => {
    if (val) {
      selectedOss.value = [];
      // 获取文件列表
      getFileList();
      init();
    }
  }, { deep: true, immediate: true })
</script>

<style lang="less" scoped>
  .oss-manage {
    height: 632px;
  }
  // 文件列表
  .file-list {
    height: 632px;
    box-sizing: border-box;
    border-right: 1px solid #e5e6eb;
    padding: 24px 0;
  }
  // 图片列表
  .pic-list {
    height: 632px;
    box-sizing: border-box;
    padding: 24px 0 24px 24px;
  }
  .search-box {
    display: flex;
    /*flex-direction: row-reverse;*/
    justify-content: space-between;
  }
  .img-box {
    width: 100%;
    height: 500px;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
    justify-content: flex-start;
    align-content: flex-start;
    margin-top: 20px;
    .img-item {
      width: 120px;
      height: 158px;
      box-sizing: border-box;
      margin: 0 26px 8px 0;
      .card {
        width: 120px;
        height: 120px;
        border-radius: 8px;
        border: 2px solid transparent;
        overflow: hidden;
        box-sizing: border-box;
        position: relative;
        img {
          width: 100%;
          height: 100%;
        }
        .checkbox {
          position: absolute;
          top: 10px;
          right: 10px;
          z-index: 1000;
        }
        .preview {
          width: 100%;
          height: 26px;
          background-color: #ffffff;
          text-align: center;
          line-height: 30px;
          color: #666666;
          position: absolute;
          left: 0;
          bottom: 0;
        }
      }
      .card:hover,
      .custom-checkbox-card-checked {
        border: 2px solid #1966ff;
      }
      .text {
        width: 120px;
        height: 36px;
        align-items: center;
        display: flex;
        justify-content: center;
        cursor: pointer;
        div {
          color: #252931;
          font-size: 14px;
          line-height: 36px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
    .img-item:nth-of-type(5n) {
      margin-right: 0;
    }
  }
  .pagination-box {
    display: flex;
    flex-direction: row-reverse;
  }

  .custom-checkbox-card {
    border: 1px solid var(--color-border-2);
    border-radius: 4px;
    width: 40px;
    height: 40px;
    box-sizing: border-box;
    position: relative;
  }

  .custom-checkbox-card-mask {
    height: 14px;
    width: 14px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 2px;
    border: 1px solid var(--color-border-2);
    box-sizing: border-box;
    position: absolute;
    top: 10px;
    right: 10px;
    background-color: #ffffff;
  }

  .custom-checkbox-card-mask-dot {
    width: 8px;
    height: 8px;
    border-radius: 2px;
  }

  .custom-checkbox-card-title {
    color: var(--color-text-1);
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 8px;
  }

  .custom-checkbox-card:hover,
  .custom-checkbox-card-checked,
  .custom-checkbox-card:hover .custom-checkbox-card-mask,
  .custom-checkbox-card-checked .custom-checkbox-card-mask {
    border-color: rgb(var(--primary-6));
  }

  .custom-checkbox-card-checked {
    background-color: var(--color-primary-light-1);
  }

  .custom-checkbox-card:hover .custom-checkbox-card-title,
  .custom-checkbox-card-checked .custom-checkbox-card-title {
    color: rgb(var(--primary-6));
  }

  .custom-checkbox-card-checked .custom-checkbox-card-mask-dot {
    background-color: rgb(var(--primary-6));
  }
  :deep(.arco-tree-node-selected) {
    background-color: #f2f3f5;
  }
  :deep(.arco-tree-node) {
    height: 36px;
    color: #19191a;
    font-size: 14px;
  }
  :deep(.arco-tree-node:hover) {
    background-color: #f2f3f5;
  }
</style>
